<script setup lang="ts">
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components'
import { LineChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { ref, watch } from 'vue'
import { listByUserSelect } from '@/utils/format'
import { showDialog, type PickerConfirmEventParams } from 'vant'
import type { WeightRecordI } from '@/types/record'
import { createWeightRecordUtil, getWeightRecordByMonthUtil } from '@/AGC/utils/record'
import dayjs from 'dayjs'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { getDays } from '@/utils'
import type { TooltipFormatterParams } from '@/types/chart'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
])
const chartRef = ref()
let chart: echarts.ECharts | null = null
let xAxisData: number[] = []
let yAxisData: number[] = []
const setXAxisData = () => {
  const result: number[] = []
  const days = getDays(monthString.value)

  for (let i = 1; i <= days; i++) {
    result.push(i)
  }
  xAxisData = result
}
const setYxisData = () => {
  const result: number[] = []
  const days = getDays(monthString.value)

  for (let i = 1; i <= days; i++) {
    const record = list.value.find(
      (item) => item.date == `${monthString.value}-${i < 10 ? '0' + i : i}`,
    )

    if (record) {
      result.push(record.weight)
    } else {
      result.push(0)
    }
  }

  // 找到第一个不为0的值
  let startIndex = 0
  for (let i = 0; i < result.length; i++) {
    if (result[i] != 0) {
      startIndex = i
      break
    }
  }

  // 找到最后一个不为0的值
  let endIndex = 0
  for (let i = result.length - 1; i >= 0; i--) {
    if (result[i] != 0) {
      endIndex = i
      break
    }
  }

  let tempValue = 0

  for (let i = startIndex; i <= endIndex; i++) {
    if (result[i] == 0) {
      if (tempValue != 0) result[i] = tempValue
      continue
    } else {
      tempValue = result[i]
    }
  }

  yAxisData = result
}
// 设置图表
const setEcharts = () => {
  chart = echarts.init(chartRef.value)
  const option = {
    title: {
      text: `${Number(monthString.value.split('-')[1])}月体重数据变化`,
    },
    legend: {
      selectedMode: false,
      data: ['体重'],
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params: TooltipFormatterParams[]) {
        let result = ''

        params.forEach((param) => {
          result += `${param.name}日<br/> 体重: ${param.value.toFixed(2)}kg<br/>`
        })

        return result
      },
    },
    grid: {
      left: '3%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      name: '日',
      boundaryGap: false,
      data: xAxisData,
      axisLine: {
        symbol: ['none', 'arrow'],
        symbolOffset: [0, 10],
      },
    },
    yAxis: {
      type: 'value',
      // 使用字符串模板，保留两位小数并自动补零
      axisLabel: {
        formatter: function (value: number) {
          return value.toFixed(2) // 或自定义逻辑
        },
      },
      name: 'kg',
      axisLine: {
        show: true,
        symbol: ['none', 'arrow'],
        symbolOffset: [0, 10],
      },
      min: 'dataMin',
    },
    series: [
      {
        name: '体重',
        type: 'line',
        stack: 'Total',
        data: yAxisData,
      },
    ],
  }
  chart.setOption(option)
}
// 今天初始体重记录
const emptyRecord: WeightRecordI = {
  id: 0,
  user_id: useUserStore().userInfo.id,
  date: dayjs().format('YYYY-MM-DD'),
  weight: 0,
}
// 今天体重记录
const todayRecord = ref<WeightRecordI>({ ...emptyRecord })
const getTodayRecord = async () => {
  const record = list.value.find((item) => item.date == emptyRecord.date)

  if (record) todayRecord.value = record
}
// 月份
const monthString = ref(dayjs().format('YYYY-MM'))
// 体重记录列表
const list = ref<WeightRecordI[]>([])
const getWeightRecordList = async () => {
  list.value = await getWeightRecordByMonthUtil(monthString.value)
  getTodayRecord()

  if (list.value.length) {
    setXAxisData()
    setYxisData()
    setEcharts()
  } else {
    chart?.clear()
  }
}
// 弹窗类型
const showPopupType = ref('')
// 打开弹窗前的逻辑事件
const beforeOpenPopup = async () => {
  const currentMonth = Number(dayjs().format('MM'))
  const chooseMonth = Number(monthString.value.split('-')[1])

  if (chooseMonth < currentMonth) {
    await showDialog({
      title: '温馨提示',
      message: '时间已经过去了, 好可惜呀',
      theme: 'round-button',
    })
  } else if (chooseMonth > currentMonth) {
    await showDialog({
      title: '温馨提示',
      message: '不要心急哦~, 时间还没到呢',
      theme: 'round-button',
    })
  } else {
    showPopupType.value = 'weight'
  }
}
// 弹窗确认事件
const onConfirm = async ({ selectedValues }: PickerConfirmEventParams) => {
  const weight = selectedValues[0].toString() + '.' + selectedValues[1].toString()
  todayRecord.value.weight = Number(weight)
  await createWeightRecordUtil(todayRecord.value)
  await getWeightRecordList()
  showPopupType.value = ''
  ElMessage.success(todayRecord.value.id ? '体重数据修改成功' : '体重数据收集成功')
}
watch(
  monthString,
  async () => {
    if (monthString.value) {
      setTimeout(async () => {
        await getWeightRecordList()
      }, 100)
    }
  },
  { immediate: true },
)
</script>

<template>
  <div style="width: 100%; position: relative">
    <div class="body-date-picker">
      <el-date-picker
        v-model="monthString"
        type="month"
        placeholder="选择月份"
        value-format="YYYY-MM"
      />
    </div>
    <div v-if="list.length == 0" class="gradient-text">
      <div class="keyword">📢小康途</div>
      还没有收集到您
      <span class="keyword">{{ Number(monthString.split('-')[1]) }}月</span>的
      <div class="keyword">体重数据哦~</div>
      <div class="link" @click="beforeOpenPopup">去收集</div>
    </div>
    <div v-else class="body-leftTop">
      <div class="gradient-day-text" v-if="!todayRecord.id">
        <span>📢</span>
        <span class="keyword">小康途</span>
        还没有收集到您
        <span class="keyword">今天</span>
        的体重数据哦~
        <span class="link" @click="showPopupType = 'weight'">去收集</span>
      </div>
      <div class="gradient-day-text" v-else>
        <span>📢</span>
        <span class="keyword">小康途</span>
        已经收集到您
        <span class="keyword">今天</span>
        的体重数据了~
        <span class="link" @click="showPopupType = 'weight'">去修改</span>
      </div>
    </div>
    <div ref="chartRef" style="width: 100%; height: 400px; margin-top: 30px"></div>
    <van-popup :show="showPopupType == 'weight'" round position="center">
      <van-picker
        title="请选择体重(kg)"
        :columns="listByUserSelect('weight')"
        @cancel="showPopupType = ''"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>

<style scoped lang="less">
// 选择月份
.body-date-picker {
  position: absolute;
  margin-left: 60%;
  margin-top: -25px;
  z-index: 100;
}
// 最初收集数据提示
.gradient-text {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
  color: black;
  font-size: 45px;
  text-align: center;
  font-family: 'Comic Sans MS', cursive, sans-serif;

  .keyword {
    color: rgb(5, 88, 229); /* 高亮颜色 */
    font-weight: bold; /* 加粗 */
  }

  .link {
    text-decoration: underline; /* 下划线 */
    cursor: pointer; /* 鼠标指针 */
  }

  .link:hover {
    color: rgb(5, 88, 229); /* 鼠标悬停时的颜色 */
  }
}

// 主体左上角
.body-leftTop {
  position: absolute;
  left: 63%;
  top: -25px;
  transform: translateX(-5%);
  z-index: 99;
  display: flex;
  width: 100%;

  // 收集今天数据提示
  .gradient-day-text {
    margin-left: -45%;
    background: linear-gradient(135deg, #ff9a9e, #fad0c4);
    padding: 10px;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    max-width: 250px;
    color: white;
    font-size: 14px;
    text-align: center;
    font-family: 'Comic Sans MS', cursive, sans-serif;

    .keyword {
      color: #ffeb3b; /* 高亮颜色 */
      font-weight: bold; /* 加粗 */
    }

    .link {
      text-decoration: underline; /* 下划线 */
      cursor: pointer; /* 鼠标指针 */
    }

    .link:hover {
      color: #ffeb3b; /* 鼠标悬停时的颜色 */
    }
  }
}

.van-popup {
  width: 30%;
}
</style>
